<template>
    <div class="goods-classify" >
        <div class="plr15 ptb10" @click="link('/pages/project2/splb?isWhole=1')">
            <div class="ptb8 bgc-f2f2f2 fs-12 c-808080 tc">输入关键字搜索</div>
        </div>
        <div class="tree-wrap">
            <van-tree-select
                :items="items"
                :main-active-index="activeIndex"
                v-on:clickNav="onClickNav"
                bind:click-item="onClickItem"
                >
                <!-- <scroll-view slot="content" class="content"> -->
                    <div slot="content" class="content">
                        <div class="barner"><img :src="categoryList[activeIndex]&&categoryList[activeIndex].img"></div>

                    <ClList 
                        :loading="loading"
                        :finished="finished"
                        finishedText="没有更多了"
                        @load="ListProduct"
                        :list="list">
                        <div class="list pt8">
                            <div class="item mb5" v-for="(item, i) in list" :key="i" @click="link('/pages/project2/spxq?id='+item.prdId)">
                                <div class="inner kitbox">
                                    <div class="photo">
                                        <img :src="item.cover" alt="">
                                        <div v-if="item.is_flash_sale" class="miaosha">秒杀</div>
                                    </div>
                                    <div class="flex1 pl10">
                                        <div class="mt5 ellipsis_2 fs-12 lh1-3 c-000 m-height">
                                            {{item.name}}
                                            <!-- <van-tag :round="true" color="#fddf32" text-color="#000000">三店通用</van-tag> -->
                                            <!-- <span class=""></span> -->
                                        </div>
                                        <div class="kitbox">
                                            <div class="flex1 pt10">
                                                <div class="c-ff3333 fs-14">¥{{item.price_str}}</div>
                                                <div class="c-a5a5a5 fs-12 mt5 old-price">¥{{item.old_price_str}}</div>
                                            </div>
                                            <div class="pt20" ><van-icon v-on:click.stop="add(item)" name="add" color="#ff6f6f" size="24px"/></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </ClList>
                    </div>
            </van-tree-select>
        </div>

        <div v-if="formShow">
        <van-action-sheet  :show="formShow" title=" " v-on:close="closeForm">
            <div class="float-panel plr15 pt10">
                <div class="kitbox ">
                    <div class="photo">
                        <img :src="product.cover" alt="">
                    </div>
                    <div class="flex1 pl10">
                        <div class="c-ff4141 pt15">￥<span class="fs-21">{{product.price_str}}</span></div>
                        <div class="pt10 fs-13 c-333 ">{{product.name}}</div>
                        <div class="pt5 c-999 fs-13">库存 {{product.remain_stock}}件</div>
                    </div>
                    
                </div>

                <div v-for="(item, i) in product.spec_cates" :key="i">
                    <div class="fs-16 c-333 ptb10">{{item.name}}</div>
                    <div class="tags">
                        <div class="tag" 
                            :class="((selItems[child.itemId])  == 1? 'active' : ((canSelItems&&canSelItems[child.itemId]==1)||!canSelItems)? '' : 'disabled')"
                            @click="selSpecs(child, item, !((canSelItems&&canSelItems[child.itemId]==1)||!canSelItems))" v-for="(child, j) in item.items" :key="j">{{child.name}}</div>
                    </div>
                </div>

                <!-- <div class="fs-16 c-333 ptb10" v-if="product.specs&&product.specs.length>0">颜色规格</div>
                <div class="tags">
                    <div class="tag" :class="{active: specs.specId==item.specId}" @click="selSpecs(item)" v-for="(item, i) in product.specs" :key="i">{{item.name}}</div>
                </div> -->

                <div class="kitbox ptb10 bt-e1e1e1 bb-e1e1e1 mb10 mt10">
                    <div class="">购买数量</div>
                    <div class="flex1 tr"><van-stepper :disable-input="true" :value="count" :max="buyLimit" v-on:change="countChange" /></div>
                </div>
                <div class="pb10 pt20">
                    <van-button v-if="product&&product.remain_stock" @click="addToCar(product)" round  color="#ff4141" size="large">确定</van-button>
                    <van-button v-else="" round   color="#999999" size="large">确定</van-button>
                </div>
            </div>
            
        </van-action-sheet>
        </div>

        <NavBar :active="1" name="index3"></NavBar>
    </div>
</template>

<script>
import productApi from "@/api/api-product";
import ClList from "@/components/ClList"
export default {
    name: "goodsClassify",
    components: {
        ClList
    },
    data(){
        return {
            items: [],
            activeIndex: 0,
            categoryList: [],
            loading: true,
            finished: false,
            pageIndex: 1,
            pageSize: 20,
            list: [],
            formShow: false,
            product: undefined,
            oldproduct: undefined,
            count: 1,

            specs: "",
            specCates: [],
            specIds: [],
            selItems:{},
            buyLimit: 0,
            canSelItems: undefined
        }
    },
    mounted() {
        this.ListCategory()
    },
    onHide(){
        
    },
    onUnload(){
        
    },
    onShow(){
        wx.hideHomeButton()
    },
    methods: {
        async ListCategory(){
            var res = await productApi.ListCategory({})
            this.categoryList = res.result
            var tmp = []
            this.categoryList.forEach(v => {
                tmp.push({text: v.name})
            });
            this.items = tmp
            this.ListProduct(true)
        },
        ListProduct(reload){
            this.loading = true
            if(reload){
                this.pageIndex = 1
                this.finished = false
            }
            productApi.ListProduct({
                cateId: this.categoryList[this.activeIndex].cate_id,
                // shopId: this.active==0? 3 : 4,//店铺id
                // layoutId: this.area&&this.area!=11? this.area : "",//店铺板块id

                // keyword: this.searchText,
                // orderby: this.orderby,
                pageIndex: this.pageIndex,
                pageSize: this.pageSize
            }).then(data => {
                this.loading = false
                if(reload){
                    this.list = data.result.List
                } else {
                    this.list = this.list.concat(data.result.List)
                }
                this.finished = data.result.IsLastPage
                this.pageIndex++
            })
        },
        onClickNav(e){
            this.activeIndex = e.mp.detail
            this.ListProduct(true)
        },
        toSub(item, i){
            this.$store.dispatch('tagsView/addCachedView', this.$route)
            var v = this.categoryList[this.activeIndex]
            sessionStorage.setItem('SUB_PAGE_PARAMS', JSON.stringify(v))
            this.$router.push({
                path: '/goods/sub',
                query: {
                    '_rs_title': item.name,
                    id: v.cat_id,
                    cid: item.cat_id,
                    ci: i
                }
            })
        },
        link(url){
            wx.navigateTo({
                url: url
            })
        },
        add(item){
            if(item.is_flash_sale){
                this.link('/pages/project2/spxq?id='+item.prdId)
                return
            }
            this.canSelItems = undefined
            this.product = item
            this.oldproduct = JSON.parse(JSON.stringify(item))
            this.buyLimit = this.product.buy_limit==0 || (this.product.buy_limit>this.product.remain_stock) ? this.product.remain_stock : this.product.buy_limit
            if(item.spec_cates&&item.spec_cates.length){
                this.formShow = true
            } else {
                this.addToCar(item, 1)
            }
        },
        addToCar(item, type){
            if(type==1){
                item.count = 1
                item.buySpecs = []
            } else {
                if(!this.specs && this.product.spec_cates&&this.product.spec_cates.length>0){
                    wx.showToast({
                        title: '请选择规格',
                        icon: 'none',
                        duration: 2000
                    })
                    return
                }
                item.buySpecs = this.specs
                item.buySpecCate = this.specCates
                item.count = this.count
            }
            
            this.$store.dispatch('addShopCar', item)
            this.closeForm()
            wx.showToast({
                title: '加入购物车成功',
                icon: 'success',
                duration: 2000
            })
        },
        countChange(e){
            if(e.mp.detail==0 || e.mp.detail>this.product.stock){
                return
            }
            this.count = e.mp.detail
        },
        accessCanSelItem(item, p){
            var items = {}
            this.product.specs.forEach(v => {
                if(v.stock == 0){
                    return
                }
                var i = 0
                this.specIds.forEach(m => {
                    if(v.itemIds.indexOf(m)!=-1){
                        i++
                    }
                })
                if( i!=0){
                    v.itemIds.split(",").forEach(m => {
                        items[m] = 1
                    })
                }
            })
            if(this.specIds.length==1){
                var spec_cate 
                this.product.spec_cates.forEach(v => {
                    v.items.forEach(m => {
                        if(m.itemId == this.specIds[0]){
                            spec_cate = v
                        }
                    })
                })
                if(spec_cate){
                    spec_cate.items.forEach(v => {
                        items[v.itemId] = 1
                    })
                }
            }
            if(JSON.stringify(items)=="{}"){
                this.canSelItems = undefined
            } else {
                this.canSelItems = items
            }
        },
        selSpecs(item, p, disabled){
            if(disabled){
                return
            }
            var has = false

            if((this.selItems[item.itemId])  == 1){
                //取消
                this.specCates.forEach(v => {
                    if(v.cateId == p.cateId){
                        if(v.child){
                            this.selItems[v.child.itemId] = 0
                            this.specIds.splice(this.specIds.indexOf(v.child.itemId), 1)
                            v.child = undefined
                        }
                    }
                });

                this.product.price = this.oldproduct.price
                this.product.price_str = this.oldproduct.price.toFixed(2)
                this.product.stock = this.oldproduct.remain_stock
                this.product.remain_stock = this.oldproduct.remain_stock
                this.buyLimit = this.product.buy_limit==0 || (this.product.buy_limit>this.product.remain_stock) ? this.product.remain_stock : this.product.buy_limit
                this.specs = ""

                this.accessCanSelItem(item, p)
                return
            }

            this.specCates.forEach(v => {
                if(v.cateId == p.cateId){
                    if(v.child){
                        this.selItems[v.child.itemId] = 0
                        this.specIds.splice(this.specIds.indexOf(v.child.itemId), 1)
                    }
                    
                    v.child = item
                    this.selItems[item.itemId] = 1
                    this.specIds.push(item.itemId)
                    has = true
                }
            });
            if(!has){
                p.child = item
                this.selItems[item.itemId] = 1
                this.specIds.push(item.itemId)
                this.specCates.push(p)
            }

            
            this.accessCanSelItem(item, p)

            if(this.specCates.length != this.product.spec_cates.length){
                this.$forceUpdate()
                return
            }

            this.product.specs.forEach(v => {
                var tmp = v.itemIds.split(",")
                var i = 0
                this.specCates.forEach(v => {
                    if(v.child&&tmp.indexOf(v.child.itemId+"")!=-1){
                        i++
                    }
                });

                if(i == tmp.length && i==this.specCates.length){
                    this.specs = v
                    this.product.price = v.price
                    this.product.price_str = v.price.toFixed(2)
                    this.product.stock = v.stock
                    this.product.remain_stock = v.stock
                    this.buyLimit = this.product.buy_limit==0 || (this.product.buy_limit>this.product.remain_stock) ? this.product.remain_stock : this.product.buy_limit
                }
            });
            this.$forceUpdate()
        },
        closeForm(){
            this.formShow = false
            this.product = undefined
            this.oldproduct = undefined
            this.count = 1

            this.specs = ""
            this.specCates = []
            this.specIds = []
            this.selItems = {}
            this.buyLimit = 0
            this.canSelItems = undefined
        }
    }
};
</script>
<style lang="scss" scope>
@import './scss/classify.scss';
</style>
